package com.netty.chat.service.impl;

import com.netty.chat.dao.UserDao;
import com.netty.chat.entity.User;
import com.netty.chat.message.MessageResponse;
import com.netty.chat.server.ChatHandler;
import com.netty.chat.service.ChatService;
import com.netty.chat.vo.ChatItem;
import com.netty.chat.vo.GroupChat;
import com.netty.chat.vo.UserInfo;
import com.netty.chat.vo.UserSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.netty.chat.constant.ChatConstant.*;
import static com.netty.chat.constant.MessageType.*;
import static com.netty.chat.server.ChatHandler.chatRecord;

@Service
public class ChatServiceImpl implements ChatService {
    @Autowired
    UserDao userDao;
    @Autowired
    ChatHandler chatHandler;
    @Override
    public List<ChatItem> getChatItems(Integer userId) {
        ArrayList<ChatItem> chatItems = new ArrayList<>();
        //查询注册的所有聊天用户
        List<User> users = userDao.selectList(null);
        Map<Integer, UserSocketChannel> userChannel = ChatHandler.userChannel;
        for (User user : users) {
            if (!user.getId().equals(userId)){
                ChatItem chatItem = new ChatItem();
                UserSocketChannel socketChannel = userChannel.get(user.getId());
                chatItem.setId(user.getId().toString());
                chatItem.setGroupChat(false);
                chatItem.setDateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd HH:mm")));
//            chatItem.setDescription();
                chatItem.setName(user.getUsername());
                chatItem.setIcon(user.getIcon());
                chatItem.setMessageType(SEND_TO_USER);
                String key = chatHandler.getKey(userId, user.getId());
                List<MessageResponse> records = chatRecord.get(key);
                chatItem.setChatRecord(records);
                if (records.size()>0){
                    chatItem.setLastMessage(records.get(records.size()-1).getInfo());
                }
                if (socketChannel==null){
                    //离线
                    chatItem.setOnline(0);
                }else {
                    //在线
                    chatItem.setOnline(1);
                }
                chatItems.add(chatItem);
            }
        }
        //群聊通道处理
        Map<String, GroupChat> groupChannel = ChatHandler.groupChannel;
        Set<Map.Entry<String, GroupChat>> set = groupChannel.entrySet();
        for (Map.Entry<String, GroupChat> entry : set) {
            Set<UserInfo> members = entry.getValue().getMembers();
            for (UserInfo member : members) {
                //判断此群聊是否包括自己
                if (member.getId().equals(userId)){
                    ChatItem chatItem = new ChatItem();
                    List<MessageResponse> records = chatRecord.get(entry.getKey());
                    chatItem.setChatRecord(records);
                    if (records.size()>0){
                        chatItem.setLastMessage(records.get(records.size()-1).getInfo());
                    }
                    GroupChat value = entry.getValue();
                    chatItem.setId(entry.getKey());
                    chatItem.setGroupChat(true);
                    chatItem.setDateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd HH:mm")));
                    chatItem.setDescription(value.getGroupDesc());
                    chatItem.setName(value.getGroupName());
                    chatItem.setIcon(value.getIcon());
                    chatItem.setMessageType(SEND_TO_GROUP);
                    chatItem.setOnline(1);
                    chatItems.add(chatItem);
                }
            }
        }
        //广播聊天室通道处理
        ChatItem chatItem = new ChatItem();
        chatItem.setId(GLOBLE_CHAT_ID);
        chatItem.setGroupChat(true);
        chatItem.setDateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd HH:mm")));
        chatItem.setName(GLOBLE_CHAT_NAME);
        chatItem.setIcon("static/images/media_04.png");
        chatItem.setOnline(1);
        chatItem.setMessageType(SEND_TO_GLOBLE);
        List<MessageResponse> records = chatRecord.get(GLOBLE_CHAT_RECORD);
        chatItem.setChatRecord(records);
        if (records.size()>0){
            chatItem.setLastMessage(records.get(records.size()-1).getInfo());
        }
        chatItems.add(chatItem);
        return chatItems;
    }

    @Override
    public Set<UserInfo> getChannelByIds(List<Integer> memberIds) {
        HashSet<UserInfo> members = new HashSet<>();
        for (Integer memberId : memberIds) {
            //TODO bug:这里不应该从userChannel集合中获取用户信息，这样只能获取到登录的用户，未登录的将无法被拉入群
            UserSocketChannel userSocketChannel = ChatHandler.userChannel.get(memberId);
            if (userSocketChannel!=null){
                members.add(userSocketChannel.getUserInfo());
            }
        }
        return members;
    }
}
